//background.js
chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['content.js']
  });
});

let isOpen = false;

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "uploadData") {
    // 假设uploadData是apiManager.js中的函数
    uploadData(message.data, message.platform, message.userLanguage, message.key, message.code, message.userId, message.ori_url).then(response => {
      sendResponse(response);
    });
    return true; // 异步发送响应
  }

  if (message.action === "login") {
    loginUser(message.username, message.password, message.accountType)
      .then(response => sendResponse({ status: "success", data: response }))
      .catch(error => sendResponse({ status: "error", message: error.message }));
    return true; // 表明你将异步地发送响应
  }

  if (message.action === "openNewTab") {
    chrome.tabs.create({ url: message.url });
  }

  if (message.action === "collectComplete") {
    console.log("采集key：" + message.key + "--状态：" + message.status);
    isOpen = message.status;
  }

  if (message.action === "processLinks") {
    processLinks(message.links);
  }

});

// background.js 或其他初始化脚本
chrome.runtime.onInstalled.addListener(function () {
  chrome.storage.local.set({ isCollectOpen: false }, function () {
    console.log('默认的 saveLabel 值已设置为 false。');
  });
});



function processLinks(links) {
  let currentTabIndex = null;


  (function openNextLink() {
    if (links.length === 0) {
      console.log("所有链接采集完成！");
      return; // 所有链接处理完毕
    }

    console.log("返回的值===" + isOpen);
    const link = links.shift();
    console.log("开始采集链接: " + link);

    // 检查是否有现有的标签页可用
    if (currentTabIndex !== null) {
      chrome.tabs.update(currentTabIndex, { url: link });
    } else {
      // 获取当前标签页的ID
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length === 0) {
          console.error("无法找到当前的活动标签页。");
          return;
        }
        currentTabIndex = tabs[0].id;
        chrome.tabs.update(currentTabIndex, { url: link });
      });
    }

    // 监听标签页更新
    function updated(tabId) {
      if (tabId === currentTabIndex) {
        // console.log("返回的值2===" + isOpen);
        setTimeout(() => {
          console.log("采集中: " + link);
          chrome.tabs.sendMessage(tabId, { action: "doBusinessOperation" }, function (response) {
            if (chrome.runtime.lastError || !response || response.action !== "operationComplete") {
              console.error("操作失败或消息错误", chrome.runtime.lastError?.message);
            } else {
              console.log("采集结束: " + link);
            }
            isOpen = false;
            openNextLink();
          });

        }, 1000); // 延迟时间可根据实际情况调整
        chrome.tabs.onUpdated.removeListener(updated); // 移除监听器以避免重复调用
      }
    }

    let maxAttempts = 10; // 最大尝试次数
    let attempts = 0; // 当前尝试次数

    let checkInterval = setInterval(() => {
      if (isOpen) {
        console.log("isOpen changed to " + isOpen + ":" + attempts);
        isOpen = false;
        attempts = 0;
        // ...执行你的逻辑...
        updated(currentTabIndex);
        clearInterval(checkInterval); // 清除定时器
      } else if (attempts >= maxAttempts) {
        attempts = 0;
        console.log("已达到最大尝试次数，停止等待。");
        clearInterval(checkInterval); // 清除定时器
        // ...执行尝试次数达到后的逻辑...
        updated(currentTabIndex);
      }
      attempts++; // 增加尝试次数
    }, 1000);


  })();
}
